﻿using MediatR;
using RBAC_Uthorization.API.Application.Command.UserRoleCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.Extensions;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using StackExchange.Redis;

namespace RBAC_Uthorization.API.Application.CommandHandlers.UserRoleHandler
{
    public class UserRoleUpdateCommandHandlers : IRequestHandler<UserRoleUpdateCommand, ApiResult<int>>
    {
        private readonly IUserRoleRepository _userRoleService;
        private readonly ILogger<UserRoleUpdateCommandHandlers> _logger;
        private readonly IConfiguration _configuration;
        private readonly RedisConnectionService _redisConnectionService;
        public UserRoleUpdateCommandHandlers(IUserRoleRepository userRoleService, ILogger<UserRoleUpdateCommandHandlers> logger, IConfiguration configuration, RedisConnectionService redisConnectionService)
        {
            _userRoleService = userRoleService;
            _logger = logger;
            _configuration = configuration;
            _redisConnectionService = redisConnectionService;
        }

        public async Task<ApiResult<int>> Handle(UserRoleUpdateCommand request, CancellationToken cancellationToken)
        {
            
          
            //先删除后添加
            try
            {
                var userRole = await _userRoleService.GetAllAsunc(x => x.role_id == request.dto.RoleId && x.del_flag == 0);
                if (userRole != null)
                {
                    foreach (var item in userRole)
                    {
                        await _userRoleService.DeleteAsync(item.id);
                    }
                }
                
                foreach (var item in request.dto.UserId)
                {

                    if (_configuration["Redis:Redisif"] == "1")
                    {
                      
                        // 删除 Redis 中的用户角色菜单
                        await _redisConnectionService.DeleteAsync($"user:{item}:{request.sys_id}:roleIds");
                        // 删除 Redis 中的菜单
                        await _redisConnectionService.DeleteAsync($"user:{item}:{request.sys_id}:menuIds");
                    }
                 
                    var userRoleAdd = new sys_user_role()
                    {
                        user_id = item,
                        role_id = request.dto.RoleId,
                        create_by = request.updateName,
                        create_date = DateTime.UtcNow,

                    };
                    await _userRoleService.AddAsync(userRoleAdd);
                }
                _logger.LogInformation($"操作人：{request.updateName},操作系统：{request.sys_id}用户角色更新成功：{request.dto}");
                return new ApiResult<int>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户角色更新异常");
                return new ApiResult<int>() { Code = ResultCode.Fail, Message = "用户角色更新异常" };
            }
        }
    }
}
